// const API_URL = "https://app.xm2auto.com:8888";
// const API_URL = "http://127.0.0.1:8888";
// const API_URL = "http://172.26.172.153:8888";   
// const API_URL = "http://172.26.172.15:8888";
// const API_URL = "http://117.29.164.86:6789/trade";
// const API_URL='http://117.29.164.86:6789';
const  API_URL='https://mall.xm2auto.com:8888';
const IMG_URL = "/common/image";


const wxRequest = (option) => {
  let url = option.url;
  if (url == null || url === "") return;
  if (url.startsWith("http://") || url.startsWith("https://")) {
    //如果路径已经包含了http，说明传入的已经是完整的访问地址，不需要再添加默认定义的系统地址
  } else {
    url = API_URL + url;
  }
  let method = option.method ? option.method : 'POST';
  console.log('sessionId', wx.getStorageSync("sessionid"))
  let header = {
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'cookie': wx.getStorageSync("sessionid") //默认所有请求都带上cookie
  };
  let promise = new Promise(function(resolve, reject) {
    wx.request({
      url: url, //自己的后台登录方法（即cortroller层的登录方法地址）
      method: method,
      data: option.data,
      header: header,
      success: function(res) {
        console.log('wx.request:',url,res);
        // console.log('request请求')
        // console.log(res)
        //说明访问成功
        if (res.data.code == 200) {
          resolve(res.data);
        } else {
          if (res.data.code == 403) {

            unLogin(Request, option);
            //login();
            //返回说明用户还未登录，并且当前返回的路径需要登录。所以跳转到登录页面
          } else {
            if (res.data.code == 'ServiceException') {
              reject(res.data.message.replace('ServiceException:', ''));

            } else {
              reject(res.data.message);

            }
          }
        }
      },
      fail: function(res) {
        reject(res.errMsg);
      }
    });
  });
  return promise;
}

const Get = (url, params) => {
  return wxRequest({
    url: url,
    data: params,
    method: 'GET'
  });
}

const Post = (url, params) => {
  return wxRequest({
    url: url,
    data: params,
    method: 'POST'
  });
}

/**
 * 发起http请求，此处封装请求，用于各个页面的调用，便于统一处理
 */
const Request = (option) => {
  wxRequest(option).then((res) => {

    if (option.success) {
      //回调传入的函数
      option.success(res.data);
    }
  }).catch((res) => {

    if (option.error) {
      option.error(res);
    } else {
      wx.showModal({
        content: "异常：" + res,
        showCancel: false
      });
    }
  })
}

const Upload = (option) => {
  let url = option.url;
  if (url == null || url === "") return;
  if (url.startsWith("http://") || url.startsWith("https://")) {
    //如果路径已经包含了http，说明传入的已经是完整的访问地址，不需要再添加默认定义的系统地址
  } else {
    url = API_URL + url;
  }
  let fileKey = option.fileKey ? option.fileKey : 'file';
  let header = {
    "Content-Type": "multipart/form-data",
    'cookie': wx.getStorageSync("sessionid") //默认所有请求都带上cookie
  };
  wx.uploadFile({
    url: url,
    filePath: option.filePath,
    name: fileKey,
    formData: option.data,
    header: header,
    success(res) {
      // console.log('传图成功')
      // console.log(res)
      var data = res.data;
      if (typeof data != 'object') {
        data = data.replace(/\ufeff/g, ""); //重点
        data = JSON.parse(data);
      }
      //说明访问成功
      if (data.code == 200) {
        if (option.success) {
          //回调传入的函数
          option.success(data.data);
        }
      } else {
        if (data.code == 403) {
          unLogin(
            Upload, option
          );
          //login();
          //返回说明用户还未登录，并且当前返回的路径需要登录。所以跳转到登录页面
        } else {
          if (option.error) {
            option.error(data.message);
          } else {
            if (data.code == 'ServiceException') {
              wx.showModal({
                content: data.message.replace('ServiceException:', ''),
                showCancel: false
              });
            } else {
              wx.showModal({
                content: data.message,
                showCancel: false
              });
            }

          }
        }
      }
    },
    fail(res) {
      if (option.error) {
        option.error(res);
      } else {
        wx.showModal({
          content: res,
          showCancel: false
        });
      }
    }
  })
}

const unLogin = (func, params) => {
  wx.getUserInfo({
    success: detail => {
      wx.login({
        success: res => {
          if (res.errMsg == "login:ok") {
            let data = {
              wxLogin: 'true', //使用微信登录标志，不需要再输入用户名密码，直接可通过微信登录
              iv: detail.iv, //公钥
              encryptedData: detail.encryptedData, //加密的信息
              jsCode: res.code //通过wx.login获取的jsCode
            };
            wx.request({
              url: API_URL + "/login", //自己的后台登录方法（即cortroller层的登录方法地址）
              method: 'POST',
              data: data,
              header: {
                'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
              },
              success: function(res) {
                if (res.data.code == 200) {
                  //说明登录成功
                  wx.setStorageSync("sessionid", res.header["Set-Cookie"].split(";")[0]);
                  Request({
                    url: "/member/findMemberUserInfo", //自己的后台登录方法（即cortroller层的登录方法地址）
                    success: function(result) {
                      wx.setStorageSync("userInfo", result);

                      // }
                    }
                  })
                  //重新登录时清除字典
                  const {deleteDicts} = require('./dict.js')
                  deleteDicts();
                  func(params);

                  //登录成功后调用回调函数，主要是为了绑定小程序和登录的帐号
                  // wx.switchTab({ url: "pages/trade/trade" });
                } else {
                  wx.removeStorage({
                    key: 'userInfo',
                    complete(res) {}
                  });
                  wx.switchTab({
                    url: '/pages/index/index'
                  });
                }
              }
            });
          }
        },
        fail: res => {},
        complete: res => {}
      });
    }
  });
  // wx.reLaunch({
  //   url: '/pages/index/index'
  // })
}

module.exports = {
  get: Get,
  post: Post,
  request: Request,
  upload: Upload,
  apiUrl: API_URL,
  imgUrl: IMG_URL
}